//
//  LLRegisterViewController.m
//  LoveLove
//
//  Created by 肖兰月 on 2019/4/11.
//  Copyright © 2019 wkf. All rights reserved.
//

#import "LLRegisterViewController.h"
#import "LLUserInfo.h"
#import "TabBarViewController.h"
#import "LLChannelModel.h"
#import "LLUserDelegateVC.h"
#import "LLDegegateView.h"

@interface LLRegisterViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) UIImageView *logoImgView;
@property (strong, nonatomic) UITextField *phoneTextField;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) LLButton *handlePwdTextFieldBtn;
@property (strong, nonatomic) UITextField *codeTextField;
@property (strong, nonatomic) LLButton *codeBtn;
@property (strong, nonatomic) LLButton *registerBtn;
@property (strong, nonatomic) LLButton *loginBtn;

@property (assign, nonatomic) BOOL isAgree;
@end

@implementation LLRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.view.backgroundColor = UIColor.whiteColor;
}

- (void)initUI {
    self.isAgree = YES;
    // logo
    CGFloat top = LLScreenWidth < 375 ? 30 : 50;
    CGFloat left = LLScreenWidth < 375 ? 40 : 50;
    CGFloat logoImgViewW = 83;
    UIImageView *topLogo = [UIImageView new];
    topLogo.frame = CGRectMake((LLScreenWidth - logoImgViewW)/2.0, 0, logoImgViewW, logoImgViewW);
    topLogo.image = [UIImage imageNamed:@"logo111"];
    [self.view addSubview:topLogo];
    
    _logoImgView = [UIImageView new];
    _logoImgView.frame = CGRectMake((LLScreenWidth - logoImgViewW)/2.0, topLogo.bottom-17, logoImgViewW, logoImgViewW);
    _logoImgView.image = [UIImage imageNamed:@"logo倒影"];
    
    [self.view addSubview:_logoImgView];
    
    CGFloat fieldH = LLScreenWidth < 375 ? 40 : 50;
    CGFloat phoneTextFieldTopMargin =  LLScreenWidth < 375 ? 10 : 20;
    // 账号输入框
    _phoneTextField = [UITextField new];
    _phoneTextField.frame = CGRectMake(left, _logoImgView.bottom + phoneTextFieldTopMargin, LLScreenWidth - left * 2, fieldH);
    _phoneTextField.placeholder = @"请输入手机号码";
    
    UIView *phoneLeftView = UIView.new;
    phoneLeftView.size = CGSizeMake(fieldH-10, fieldH);
    UIImageView *phoneImgView = [UIImageView new];
    phoneImgView.frame = CGRectMake(10, (fieldH-17)/2.0, 12, 17);
    phoneImgView.image = [UIImage imageNamed:@"手机icon"];
    [phoneLeftView addSubview:phoneImgView];
    
    _phoneTextField.leftView = phoneLeftView;
    _phoneTextField.leftViewMode = UITextFieldViewModeAlways;
    _phoneTextField.tag = 0;
    _phoneTextField.font = [UIFont systemFontOfSize:15];
    _phoneTextField.delegate = self;
    _phoneTextField.tintColor = LLColor(225, 0, 0);
    _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _phoneTextField.inputAccessoryView = [UIView new];
    _phoneTextField.keyboardType = UIKeyboardTypeASCIICapableNumberPad;
//    [_phoneTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_phoneTextField];
    CALayer *line1 = [CALayer layer];
    line1.frame = CGRectMake(left, _phoneTextField.bottom, LLScreenWidth - left * 2, 0.5);
    line1.backgroundColor = LLColorRGB(153).CGColor;
    [self.view.layer addSublayer:line1];
    
    //操作密码输入框的按钮
    _handlePwdTextFieldBtn = [LLButton new];
    _handlePwdTextFieldBtn.frame = CGRectMake(LLScreenWidth-40-left, _phoneTextField.bottom+10, 40, fieldH);
    [_handlePwdTextFieldBtn setImage:[UIImage imageNamed:@"睁眼"] forState:0];
    [_handlePwdTextFieldBtn setImage:[UIImage imageNamed:@"闭眼"] forState:UIControlStateSelected];
    _handlePwdTextFieldBtn.selected = YES;
    [self.view addSubview:_handlePwdTextFieldBtn];
    [_handlePwdTextFieldBtn addTarget:self action:@selector(handlePwdTextFieldBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 密码输入框
    _passwordTextField = [UITextField new];
    _passwordTextField.frame = CGRectMake(left, _phoneTextField.bottom + 10, _handlePwdTextFieldBtn.left-left, fieldH);
    _passwordTextField.placeholder = @"请输入密码";
    
    UIView *pwdLeftView = UIView.new;
    pwdLeftView.size = CGSizeMake(fieldH-10, fieldH);
    UIImageView *pwdImgView = [UIImageView new];
    pwdImgView.frame = CGRectMake(10, (fieldH-15)/2.0, 13, 15);
    pwdImgView.image = [UIImage imageNamed:@"密码icon"];
    [pwdLeftView addSubview:pwdImgView];
    
    _passwordTextField.leftView = pwdLeftView;
    _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
    _passwordTextField.tag = 1;
    _passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _passwordTextField.returnKeyType = UIReturnKeyDone;
    _passwordTextField.delegate = self;
    _passwordTextField.tintColor = LLColor(225, 0, 0);
    _passwordTextField.inputAccessoryView = [UIView new];
    _passwordTextField.secureTextEntry = YES;
    _passwordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    _passwordTextField.font = [UIFont systemFontOfSize:15];
//    [_passwordTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_passwordTextField];
    CALayer *line2 = [CALayer layer];
    line2.frame = CGRectMake(left, _passwordTextField.bottom, LLScreenWidth - left * 2, 0.5);
    line2.backgroundColor = LLColorRGB(153).CGColor;
    [self.view.layer addSublayer:line2];
    
    // 验证码按钮
    _codeBtn = [LLInitBaseViewTool buttonWithTitle:@"获取验证码" image:nil titleColor:LLColor(225, 0, 0) font:15];
    _codeBtn.frame = CGRectMake(LLScreenWidth-100-left, _passwordTextField.bottom+30, 100, fieldH);
    _codeBtn.layer.cornerRadius = 8;
    _codeBtn.layer.borderColor = LLColor(225, 0, 0).CGColor;
    _codeBtn.layer.borderWidth = 1;
    [_codeBtn addTarget:self action:@selector(codeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_codeBtn];
    
    //验证码输入框
    _codeTextField = [UITextField new];
    _codeTextField.frame = CGRectMake(left, _codeBtn.top, _codeBtn.left-left-15, fieldH);
    _codeTextField.layer.borderWidth = 1;
    _codeTextField.layer.borderColor = LLColorRGB(171).CGColor;
    _codeTextField.layer.cornerRadius = 8;
    _codeTextField.placeholder = @"请输入验证码";
    _codeTextField.tag = 2;
    _codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _codeTextField.returnKeyType = UIReturnKeyDone;
    _codeTextField.delegate = self;
    _codeTextField.tintColor = LLColor(225, 0, 0);
    _codeTextField.inputAccessoryView = [UIView new];
    _codeTextField.textAlignment = NSTextAlignmentCenter;
    _codeTextField.keyboardType = UIKeyboardTypeASCIICapable;
    _codeTextField.font = [UIFont systemFontOfSize:15];
//    [_codeTextField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:_codeTextField];
    
    CGFloat noteLblY = LLScreenWidth < 375 ? LLScreenHeight-self.navH-75 : LLScreenHeight-self.navH-90;
    CGFloat noteLblLeft = (LLScreenWidth-120)/2.0;
    UILabel *noteLbl = [LLInitBaseViewTool labelWithText:@"已有账号，" textColor:LLColorRGB(160) font:13 textAlignment:NSTextAlignmentRight];
    noteLbl.frame = CGRectMake(noteLblLeft, noteLblY, 68, 20);
    [self.view addSubview:noteLbl];
    
    
    
    
    LLButton *loginBtn = [LLInitBaseViewTool buttonWithTitle:@"立即登录" image:nil titleColor:LLColor(220, 0, 0) font:13];
    loginBtn.frame = CGRectMake(noteLbl.right, noteLblY, 55, 20);
    [loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
   
    
    // 注册按钮
    _registerBtn = [LLInitBaseViewTool buttonWithTitle:@"注 册" image:nil titleColor:[UIColor whiteColor] font:17];
    _registerBtn.frame = CGRectMake(left, noteLbl.top-38-20, LLScreenWidth-left*2, 38);
    [_registerBtn setBackgroundColor:LLColor(225, 0, 0)];
    _registerBtn.layer.cornerRadius = 19;
    [_registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerBtn];
    
//    UIButton *userAgreementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    userAgreementBtn.frame = CGRectMake(left, _registerBtn.top-38-20, LLScreenWidth-left*2, 38);
//     [self.view addSubview:userAgreementBtn];
//    [userAgreementBtn setTitleColor:LLColor(220, 0, 0) forState:UIControlStateNormal];
//    [userAgreementBtn setTitle:@"《用户协议》" forState:UIControlStateNormal];
//    userAgreementBtn.titleLabel.font = [UIFont systemFontOfSize:12];;
//    [userAgreementBtn addTarget:self action:@selector(clickButton) forControlEvents:UIControlEventTouchUpInside];
    
    LLDegegateView *delegateView = [[LLDegegateView alloc]initWithFrame:CGRectMake(0, _registerBtn.top-38-20 + 10, _handlePwdTextFieldBtn.left-left, fieldH)];
    [self.view addSubview:delegateView];
    
    __weak typeof(self) weakSelf = self;
    delegateView.clickBlock = ^(NSInteger type, BOOL isAgree) {

        if (type == 1) {

            LLUserDelegateVC *vc = [LLUserDelegateVC new];
            vc.url = @"http://www.haoaih.com/h5/index/archive?id=1";
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else if (type == 2){

            LLUserDelegateVC *vc = [LLUserDelegateVC new];
            vc.url = @"http://www.haoaih.com/h5/index/archive?id=2";
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        else{
            
            weakSelf.isAgree = isAgree;
        }
    };
}

-(void)clickButton{
    LLUserDelegateVC *vc = [LLUserDelegateVC new];
    vc.url = @"http://www.haoaih.com/h5/index/archive?id=1";
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - private method

- (void)handlePwdTextFieldBtnClick:(LLButton *)btn {
    _handlePwdTextFieldBtn.selected = !_handlePwdTextFieldBtn.isSelected;
    [self.passwordTextField setSecureTextEntry:!self.passwordTextField.secureTextEntry];
    NSString *tempStr = _passwordTextField.text;
    _passwordTextField.text = nil;
    _passwordTextField.text = tempStr;
}

- (void)codeBtnClick:(UIButton *)button{
    if (self.phoneTextField.text.length == 0) {
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入手机号~"];
        [SVProgressHUD dismissWithDelay:1];
    }else{
        [self startTime:button];
        [self getCode];
    }
   
}

- (void)registerBtnClick {
    
    if (self.phoneTextField.text.length == 0) {
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入手机号~"];
        [SVProgressHUD dismissWithDelay:1];
    }else if (self.passwordTextField.text.length == 0){
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入密码~"];
        [SVProgressHUD dismissWithDelay:1];
    }else if (self.codeTextField.text.length == 0){
        [self showSVProgressHUDInfoWithsStatus:@"您还未输入验证码~"];
        [SVProgressHUD dismissWithDelay:1];
    }else if (!self.isAgree){
        [self showSVProgressHUDInfoWithsStatus:@"请同意用户协议~"];
        [SVProgressHUD dismissWithDelay:1];
    }else{
        [self sendRegisterQuest];
    }
    
}

- (void)loginBtnClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark====获取验证码
-(void)getCode{
    NSDictionary *dic = @{@"edu_id":@"1",@"mobile":self.phoneTextField.text,@"type":@"reg"};
    
    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {
        [self showSVProgressHUDInfoWithsStatus:@"验证码已发送~"];
        [SVProgressHUD dismissWithDelay:1];
    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
      
    }];
}
#pragma mark====注册
-(void)sendRegisterQuest{

    NSMutableArray *arr1 = [NSMutableArray array];
    for (LLChannelModel *model in self.tagArray) {
        [arr1 addObject:model.interestId];
    }
    
    NSDictionary *dic = @{@"edu_id":@"2",@"mobile":self.phoneTextField.text,@"pwd":self.passwordTextField.text,@"code":self.codeTextField.text,@"interest":@[]};
    
    [LLHttpTool post:LLHOST headParams:nil params:dic success:^(NSDictionary *result) {

        if ([result[@"code"] intValue] == 0) {

            [LLUserInfo saveUserInfoToLocal:result[@"data"]];

            [[LLUserInfo alloc] initWithDic:result[@"data"]];

            [self showSVProgressHUDInfoWithsStatus:@"注册成功~"];
            [SVProgressHUD dismissWithDelay:1];
            TabBarViewController *vc = [TabBarViewController new];
            [UIApplication sharedApplication].delegate.window.rootViewController = vc;
        }
        else {

            [SVProgressHUD showErrorWithStatus:result[@"msg"]];
        }

    } failure:^(NSString *msg) {
        [SVProgressHUD showErrorWithStatus:msg];
        
    }];
}

/**
 倒计时

 @param _l_timeButton 按钮
 */
-(void)startTime:(UIButton*)_l_timeButton{
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [_l_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _l_timeButton.userInteractionEnabled = YES;
            });
        }else{
            int seconds = timeout % 100;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [_l_timeButton setTitle:[NSString stringWithFormat:@"稍等%@秒",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _l_timeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
@end
